#!/usr/bin/python
#-*-coding: utf-8-*-
import sys, os
import socket, select
import time
from collections import namedtuple

Address = namedtuple('Address', ['ip', 'port'])

def start_service(listening_port, dat_to_write="empfangener_text.txt", listening_ip=""):
    """Initiiert das Warten auf UDP Pakete"""

    listening_address = Address(listening_ip, listening_port)
    s = None
    file_to_write = None
    path_fw = '/'.join([os.getcwd(), dat_to_write])

    try:
        file_to_write = file(path_fw, 'a') 
        print 'Hallo, bitte schick mir was.'
        while True:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.bind(listening_address)
            # schlecht! viele daten gehen verloren

            data, addr = s.recvfrom(1024)
            file_to_write.write(data)
            print data
  #          time.sleep(0.1)
    except IOError:
        print 'Datei %s ist nicht schreibbar' % dat_to_write
    finally:
        if s:
            s.close()
        if file_to_write:
            file_to_write.flush()
            file_to_write.close()

if __name__ == '__main__':
    listening_ip = ''
    dat_to_write = 'empfangen.txt'
    listening_port = 1111
    start_service(listening_port, dat_to_write, listening_ip)
        
